<?php
namespace Home\Controller;

use Think\Controller;

Vendor("Wxapplet.wechat");

class WechatController extends Controller
{
  public function __construct()
  {
    parent::__construct();
  }

  public function index()
  {
    $options = array(
      'token'=>'',
      'encodingaeskey'=>''
    );
    $weObj = new \Wechat($options);

    $weObj->valid();
    $type = $weObj->getRev()->getRevType();
    $event = $weObj->getRevEvent();

    if ($event['event'] == 'subscribe') {

      $openid = $weObj->getRev()->getRevFrom();
      $userinfo = get_wechat_user_info($openid);

      if ($userinfo['unionid']) {
        $map = array('union_id' => $userinfo['unionid']);
        $result = M('users')->where($map)->save(['openid' => $openid]);
      }
    }
  }
}